package casa.depesos.app.com.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.common.base.task.SilentTask;
import com.common.base.task.TaskEngine;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.support.toast.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import casa.depesos.app.com.App;
import casa.depesos.app.com.R;
import casa.depesos.app.com.databinding.ActivityBankBinding;
import casa.depesos.app.com.frag.BankCodeFragment;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.GetCodeBean;
import casa.depesos.app.com.http.data.Bank;
import casa.depesos.app.com.http.data.BankInfo;
import casa.depesos.app.com.http.req.GetBankReq;
import casa.depesos.app.com.http.req.GetWhiteReq;
import casa.depesos.app.com.http.req.SaveCardReq;
import casa.depesos.app.com.it.TextChangeListener;
import casa.depesos.app.com.utils.Constant;
import casa.depesos.app.com.utils.Report;
import casa.depesos.app.com.utils.Utils;

public class BankActivity extends BaseChooseActivity {

    ActivityBankBinding binding;
    HashMap map = new HashMap();
    BankCodeFragment fragment;
    ArrayList<Bank> list;
    Bank bank;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Report.show("ACTION_NN_001");
        binding = ActivityBankBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!needKeep()) {
            binding.tip.setVisibility(View.GONE);
            binding.bg.setBackgroundResource(R.drawable.login_bg);
        }
        binding.top.top.setPadding(0, Utils.getStatusBarHeight(this), 0, 0);
        binding.top.title.setText("Verificación de tarjeta bancaria");
        binding.top.back.setOnClickListener(v -> {
            Report.click("ACTION_NN_002");
            if (needKeep()) {
                dealBack();
            } else {
                finish();
            }
        });

        if (Constant.white) {
            try {
                BankInfo info = new GetWhiteReq().req().getData().bank;
                map.put("type", info.type);
                map.put("name", info.name);
                map.put("number", info.no);
            } catch (Throwable e) {
                e.printStackTrace();
            }
            binding.sms.setVisibility(View.GONE);
        } else {
            map.put("type", "1");
        }

        binding.type.setListener(new TextChangeListener() {
            @Override
            public void onTextChange(String txt, int index) {
                map.put("type", index + "");
                binding.bank.onTextChange(0);
            }
        });
        chooseValue(binding.type, R.array.card_type, map, "type", "Tipo de cuenta bancaria");

        if ("2".equalsIgnoreCase((String) map.get("type"))) {
            binding.type.setText(getResources().getStringArray(R.array.card_type)[1]);
        } else {
            binding.type.setText(getResources().getStringArray(R.array.card_type)[0]);
        }

        binding.bank.setListener(new TextChangeListener() {
            @Override
            public void onTextChange(String txt, int index) {
                if (index - 1 >= 0) {
                    bank = list.get(index - 1);
                    map.put("bank", bank);
                }
                if ("1".equals(map.get("type"))) {
                    Utils.setEditTextInputSpace(binding.number, 18);
                } else {
                    Utils.setEditTextInputSpace(binding.number, 16);
                }
            }
        });


        String str = String.format(getString(R.string.send_to), Utils.getPhone2());
        binding.codeTip.setText(str);

        fragment = new BankCodeFragment().setParam(binding.codeTip);
        replaceFragment(R.id.container, fragment);

        binding.next.setOnClickListener(v -> {
            next();
        });

        init();
    }

    private void init() {
        showLoading(false);
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                list = new GetBankReq().getBanks();
                h.post(new Runnable() {
                    @Override
                    public void run() {
                        hideLoading();
                        if (list == null || list.isEmpty()) {
                            ToastUtil.showShortToast(BankActivity.this, "No se obtuvo ninguna lista de bancos");
                            finish();
                            return;
                        }
                        binding.bank.setOnClickListener(v -> {
                            Intent i = new Intent(BankActivity.this, BankListActivity.class);
                            i.putParcelableArrayListExtra("banks", list);
                            startActivityForResult(i, 10);
                        });
//                            chooseValue(binding.bank, list, map, "name", "Nombre del banco");
                        String name = map.containsKey("name") ? map.get("name").toString() : "";

                        boolean found = false;
                        if (TextUtils.isEmpty(name)) {
                            binding.bank.setText("");
                        } else {
                            int index = 0;
                            for (int i = 0; i < list.size(); i++) {
                                Bank item = list.get(i);
                                if (item.name.equalsIgnoreCase(name)) {
                                    found = true;
                                    binding.bank.setText(name);
                                    index = i;
                                    break;
                                }
                            }
                            if (!found) {
                                index = 0;
                                binding.bank.setText(list.get(0).name);
                            }
                            binding.bank.onTextChange(index + 1);
                        }
                        binding.number.addTextChangedListener(new TextWatcher() {
                            boolean report = false;

                            @Override
                            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                            }

                            @Override
                            public void onTextChanged(CharSequence s, int start, int before, int count) {

                            }

                            @Override
                            public void afterTextChanged(Editable s) {
                                if (!report && s.toString().trim().length() > 0) {
                                    report = true;
                                    Report.click("ACTION_NN_003");
                                }
                                check();
                            }
                        });
                        if (found && map.containsKey("number")) {
                            binding.number.setText((String) map.get("number"));
                        }
                    }
                });
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10) {
            if (resultCode == RESULT_OK) {
                Bank item = data.getParcelableExtra("bank");
                map.put("bank", item);
                binding.bank.setText(item.name);
                if ("1".equals(map.get("type"))) {
                    Utils.setEditTextInputSpace(binding.number, 18);
                } else {
                    Utils.setEditTextInputSpace(binding.number, 16);
                }
            }
        }
    }

    private String checkNumber() {
        String txt = binding.number.getText().toString().trim();
        int len = txt.length();
        if ("1".equals(map.get("type"))) {
            if (len == 18) {
                return null;
            }
            return "Ingrese número de cuenta bancaria de 18 dígitos.";
        } else {
            if (len == 16) {
                return null;
            }
            return "Ingrese número de cuenta bancaria de 16 dígitos.";
        }
    }

    @Override
    public void check() {
        binding.codeErr.setVisibility(View.GONE);
        binding.noErr.setVisibility(View.GONE);
        fragment.showTip();
        if (checkNumber() == null && fragment.validCode()) {
            binding.next.setAlpha(1f);
        } else {
            binding.next.setAlpha(0.6f);
        }
    }

    private void next() {
        Report.click("ACTION_NN_005");
        boolean valid = true;
        if (!fragment.validCode()) {
            fragment.hideTip();
            binding.codeErr.setVisibility(View.VISIBLE);
            valid = false;
        } else {
            fragment.showTip();
            map.put("code", fragment.getSmsCode());
            binding.codeErr.setVisibility(View.GONE);
        }
        String tmp = checkNumber();
        if (tmp != null) {
            binding.noErr.setVisibility(View.VISIBLE);
            binding.noErr.setText(tmp);
            valid = false;
        } else {
            map.put("number", binding.number.getText().toString().trim());
            binding.noErr.setVisibility(View.GONE);
        }
        if (!valid) {
            return;
        }
        if (Constant.white) {
            submit();
        } else {
            toSubmit();
        }
    }

    private void toSubmit() {
        XXPermissions.with(this).permission(Permission.READ_SMS, Permission.RECEIVE_SMS, Permission.ACCESS_COARSE_LOCATION, Permission.READ_PHONE_STATE).request(new OnPermissionCallback() {
            boolean deal = false;

            @Override
            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                next(allGranted, false);
            }

            @Override
            public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                next(false, doNotAskAgain);
            }

            void next(boolean granted, boolean doNotAsk) {
                if (deal) {
                    return;
                }
                deal = true;
                if (!granted) {
                    ToastUtil.showLongToast(App.getApp(), "Asegúrese de que los permisos de SMS, ubicación y dispositivo estén habilitados, de lo contrario, puede habilitarlos en Configuración");
                    return;
                }
                submit();
            }
        });
    }

    private void submit() {
        showLoading();
        if (getIntent().getIntExtra("from", 0) == 2) {
            Report.toMone();
        }
        new SaveCardReq(map).req(new ReqCallback<GetCodeBean>() {
            @Override
            public void callback(boolean success, GetCodeBean bean) {
                hideLoading();
                if (Constant.white || success && bean.isValid()) {
                    if (getIntent().getIntExtra("from", 0) == 1) {
                        //from my bank card --> add card
                        ToastUtil.showShortToast(BankActivity.this, "Agregado exitosamente");
                        setResult(RESULT_OK);
                        finish();
                    } else {
                        if (Constant.white) {
                            Utils.setStatus(61);
                        }
                        Intent i = new Intent(BankActivity.this, CheckActivity.class);
                        startActivity(i);
                        finish();
                    }
                }
            }
        });
    }

    @Override
    protected boolean needKeep() {
        if (getIntent().getIntExtra("from", 0) == 1) {
            return false;
        }
        return true;
    }
}
